import pandas as pd
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import silhouette_score
import matplotlib.pyplot as plt

# 加载数据
df = pd.read_csv('./scenic_data.csv')

# 提取特征并标准化
features = df[['non_weekend_ratio', 'out_province_ratio', 'elderly_ratio']]  # 修正特征列名
scaler = StandardScaler()
scaled_features = scaler.fit_transform(features)

# 计算不同簇数量下的轮廓系数
scores = []
for k in range(2, 6):
    kmeans = KMeans(n_clusters=k, random_state=42)
    labels = kmeans.fit_predict(scaled_features)
    scores.append(silhouette_score(scaled_features, labels))

# 绘制轮廓系数图
plt.figure(figsize=(10, 6))
plt.plot(range(2, 6), scores, marker='o')
plt.xlabel("簇数量")
plt.ylabel("轮廓系数")
plt.title("轮廓系数与簇数量的关系")
plt.grid(True)
plt.show()

# 使用K-means聚类（基于最佳簇数量）
kmeans = KMeans(n_clusters=4, random_state=42)  # 假设根据轮廓系数选择的最佳簇数量为4
df['cluster'] = kmeans.fit_predict(scaled_features)

# 打印每个旅游机构对应的聚类结果，确保支持UTF-8编码输出
print(df[['tourist_agency_name', 'cluster']].to_string(index=False, encoding='utf-8'))

# 如果需要保存结果到新的CSV文件
df.to_csv('scenic_data_with_clusters.csv', index=False, encoding='utf-8')